import { useStore } from '@/hooks';
import * as api_account from '@/services/account';
import { Form, Input, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useState } from 'react';
import styles from './LoginBlock.module.scss';
import { useInterval } from './utils';

const { Item } = Form;
const DEFAULT_DATA = {
  name: '',
  password: '',
  autoLogin: true,
  phone: '',
  code: '',
};

const layout = {
  height: 45,
};
const LoginBlock = (
  props = {
    dataSource: DEFAULT_DATA,
  },
) => {
  const { loginStore } = useStore();
  const { dataSource = DEFAULT_DATA } = props;
  const [postData, setValue] = useState(dataSource);
  const [isRunning, checkRunning] = useState(false);
  const [isPhone, checkPhone] = useState(true);
  const [second, setSecond] = useState(59);
  const [loading, setLoading] = useState(false);
  const [code, setCode] = useState({
    captcha: '',
    captchaKey: '',
  });
  useInterval(
    () => {
      setSecond(second - 1);
      if (second <= 0) {
        checkRunning(false);
        setSecond(59);
      }
    },
    isRunning ? 1000 : null,
  );

  const formChange = (values) => {
    setValue(values);
  };
  React.useEffect(() => {
    api_account.authCode().then((x) => {
      setCode(x);
    });
  }, []);
  const sendCode = async (values, errors) => {
    if (errors) {
      return;
    }
    const { mobile } = values;
    checkRunning(true);
    try {
      await api_account.getPhoneCode({
        mobile, type: 0, tenantId: global.TENANT,
      });
    } catch (error) {
      console.log('错误', error);
    }
  };

  const handleSubmit = (values, errors) => {
    if (errors) {
      console.log('errors', errors);
      return;
    }
    setLoading(true);
    const { mobile, vcode } = values;
    loginStore
      .authSms({
        ...values,
        mobile,
        vcode,
        scope: global.SCOPE,
        tenantId: global.TENANT,
      })
      .then((_) => {
        if (values?.username !== 'admin') {
          persist.setItem('password', values?.password);
        }
        Message.success(t`登录成功!`);
        setLoading(false);
        window.location.reload();
      })
      .catch((err) => {
        console.log('🚀 _ file: LoginBlock.jsx:92 _ err:', err);
        setLoading(false);
        let errTip = '登录失败';
        const { source } = err;

        // 删除登录所需数据
        loginStore.reject_logout_init();

        if (err.message === '401') {
          errTip = t`您没有权限登录`;
        } else if (err.message === '403') {
          errTip = t`管理群未启用，登录失败`;
        } else {
          switch (source?.code) {
            case 10400:
              errTip = t`无效的验证码`;
              break;
            default:
              if (source?.code === 10401 && source?.message === 'User disabled.') {
                errTip = t`公司被禁用`;
              } else if (source?.code === 10401 && source?.message === 'Invalid credential.') {
                errTip = t`密码错误`;
              } else if (source?.code === 10401 && source?.message === 'User not found.') {
                errTip = t`用户不存在`;
              } else {
                errTip = t`登录失败`;
              }
              break;
          }
        }
        Message.warning({ content: errTip, duration: 5000 });
      });
  };

  // 自定义校验函数
  const customValidator = (rule, value, callback) => {
    const telRegex = /^(1[3-9]\d{9}$)|(^\+852[569]\d{7}$)/;
    if (!value) {
      callback('必填');
    } else if (!telRegex.test(value)) {
      callback('不是合法的电话号码');
    } else {
      callback(); // 校验通过
    }
  };

  const phoneForm = (
    <>
      <Item
        // format="tel"
        // required
        // requiredMessage={t`必填`}
        asterisk={false}
        style={layout}
        validator={customValidator}
      >
        <Input
          name="mobile"
          innerBefore={
            <span className={styles.innerBeforeInput}>
              +86
              <span className={styles.line} />
            </span>
          }
          //   maxLength={20}
          placeholder={t`手机号`}
        />
      </Item>
      <Item
        required
        requiredMessage="必填"
        style={layout}
      >
        <Input
          name="vcode"
          innerAfter={
            <span className={styles.innerAfterInput}>
              <span className={styles.line} />
              <Form.Submit
                text
                type="primary"
                style={{
                  width: 64,
                }}
                disabled={!!isRunning}
                validate={['phone']}
                onClick={sendCode}
                className={styles.sendCode}
              >
                {isRunning ? `${second}秒后再试` : t`获取验证码`}
              </Form.Submit>
            </span>
          }
          //   maxLength={20}
          placeholder={t`验证码`}
        />
      </Item>
    </>
  );
  const changeImg = () => {
    api_account.authCode().then((x) => {
      setCode(x);
    });
  };
  const accountForm = (
    <>
      <Item required requiredMessage="必填" style={layout}>
        <Input name="username" placeholder={t`用户名`} />
      </Item>
      <Item required requiredMessage="必填" style={layout}>
        <Input.Password name="password" htmlType="password" placeholder={t`密码`} />
      </Item>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <Item required requiredMessage="必填" style={layout}>
          <Input name="captchaCode" placeholder={t`验证码`} />
        </Item>
        <img src={code.captcha} height={40} alt={t`验证码`} style={{ cursor: 'pointer' }} onClick={changeImg} />
      </div>
    </>
  );

  return (
    <div>
      <div className={styles.innerBlock}>
        <div
          style={{ color: '#126be9', fontWeight: 'bold', fontSize: 24, textAlign: 'center', margin: 20 }}
        >{t`用户登录`}
        </div>
        <Form
          value={postData}
          onChange={formChange}
          size="large"
        >
          {isPhone ? phoneForm : accountForm}

          <div className={styles.infoLine}>
            <Item
              style={{
                marginBottom: 10,
              }}
            />
          </div>

          <Item
            style={{
              marginBottom: 10,
            }}
          >
            <Form.Submit
              loading={loading}
              type="primary"
              htmlType="submit"
              onClick={handleSubmit}
              className={styles.submitBtn}
              validate
            >
              {t`登录`}
            </Form.Submit>
          </Item>
        </Form>
      </div>
    </div>
  );
};

export default LoginBlock;
